package org.korosoft.rusalad.syncnrun.tools;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicLong;

/**
 * {@link java.io.OutputStream} wrapper counting sent data
 *
 * @author Dmitry Korotkov
 * @since 1.0
 */
public class CounterOutputStream extends OutputStream {
    private static final Log log = LogFactory.getLog(CounterInputStream.class);

    private final OutputStream wrapped;
    private final AtomicLong writtenBytes = new AtomicLong();

    public CounterOutputStream(OutputStream wrapped) {
        this.wrapped = wrapped;
    }

    public void write(int b) throws IOException {
        wrapped.write(b);
        writtenBytes.incrementAndGet();
    }

    public void write(byte[] b) throws IOException {
        wrapped.write(b);
        writtenBytes.addAndGet(b.length);
    }

    public void write(byte[] b, int off, int len) throws IOException {
        wrapped.write(b, off, len);
        writtenBytes.addAndGet(len);
    }

    public void flush() throws IOException {
        wrapped.flush();
    }

    public void close() throws IOException {
        wrapped.close();
        if (log.isInfoEnabled()) {
            log.info(String.format("Transferred %d bytes over the network", writtenBytes.get()));
        }
    }
}
